﻿#include "StationAdminDialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include "Global_Class.h"
#include "stations.h"

//StationAdminDialog::StationAdminDialog(QWidget* parent)
//    : QDialog(parent)
//{
//    setWindowTitle("车站信息管理");
//    QVBoxLayout* mainLayout = new QVBoxLayout(this);
//    table = new QTableWidget(this);
//    table->setColumnCount(2);
//    table->setHorizontalHeaderLabels({"车站ID", "车站名称"});
//    table->setSelectionBehavior(QAbstractItemView::SelectRows);
//    mainLayout->addWidget(table);
//    QHBoxLayout* inputLayout = new QHBoxLayout();
//    idEdit = new QLineEdit(this);
//    idEdit->setPlaceholderText("车站ID");
//    nameEdit = new QLineEdit(this);
//    nameEdit->setPlaceholderText("车站名称");
//    inputLayout->addWidget(idEdit);
//    inputLayout->addWidget(nameEdit);
//    addBtn = new QPushButton("添加", this);
//    editBtn = new QPushButton("修改", this);
//    deleteBtn = new QPushButton("删除", this);
//	undoBtn = new QPushButton("撤销", this);
//	redoBtn = new QPushButton("恢复", this);
//    inputLayout->addWidget(addBtn);
//    inputLayout->addWidget(editBtn);
//    inputLayout->addWidget(deleteBtn);
//	inputLayout->addWidget(undoBtn);
//	inputLayout->addWidget(redoBtn);
//    mainLayout->addLayout(inputLayout);
//    QHBoxLayout* searchLayout = new QHBoxLayout();
//    searchEdit = new QLineEdit(this);
//    searchEdit->setPlaceholderText("按名称查询");
//    searchBtn = new QPushButton("查询", this);
//    searchLayout->addWidget(searchEdit);
//    searchLayout->addWidget(searchBtn);
//    mainLayout->addLayout(searchLayout);
//    infoLabel = new QLabel(this);
//    mainLayout->addWidget(infoLabel);
//    refreshStationTable();
//    connect(addBtn, &QPushButton::clicked, this, &StationAdminDialog::onAddStation);
//    connect(deleteBtn, &QPushButton::clicked, this, &StationAdminDialog::onDeleteStation);
//    connect(editBtn, &QPushButton::clicked, this, &StationAdminDialog::onEditStation);
//    connect(searchBtn, &QPushButton::clicked, this, &StationAdminDialog::onSearchStation);
//	connect(undoBtn, &QPushButton::clicked, this, [this]() {
//        if (undoRedo.undoAction()) {
//            refreshStationTable();
//            showInfo("撤销成功");
//        } else {
//            showInfo("没有可撤销的操作");
//        }
//		});
//    connect(redoBtn, &QPushButton::clicked, this, [this]() {
//        if (undoRedo.redoAction()) {
//            refreshStationTable();
//            showInfo("恢复成功");
//        } else {
//            showInfo("没有可恢复的操作");
//        }
//        });
//}
StationAdminDialog::StationAdminDialog(QWidget* parent)
    : QDialog(parent)
{
    setWindowTitle("车站信息管理");
    // 设置窗口最小尺寸，避免拉伸变形
    setMinimumSize(800, 600);
    // 统一字体，提高可读性
    QFont globalFont("Microsoft YaHei", 10);
    setFont(globalFont);

    // 主布局设置边距和间距，避免拥挤
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(15, 15, 15, 15);
    mainLayout->setSpacing(12);

    // 表格控件
    table = new QTableWidget(this);
    table->setColumnCount(2);
    table->setHorizontalHeaderLabels({"车站ID", "车站名称"});
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 表格自适应列宽
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 去掉表格内部边框，优化视觉效果
    table->setShowGrid(false);
    table->verticalHeader()->setVisible(false); // 隐藏行号
    mainLayout->addWidget(table);

    // 输入和按钮布局
    QHBoxLayout* inputLayout = new QHBoxLayout();
    inputLayout->setSpacing(10); // 控件间距

    // 车站ID输入框
    idEdit = new QLineEdit(this);
    idEdit->setPlaceholderText("车站ID");
    idEdit->setMinimumWidth(120);
    inputLayout->addWidget(idEdit);

    // 车站名称输入框
    nameEdit = new QLineEdit(this);
    nameEdit->setPlaceholderText("车站名称");
    nameEdit->setMinimumWidth(180);
    inputLayout->addWidget(nameEdit);

    // 功能按钮
    addBtn = new QPushButton("添加", this);
    editBtn = new QPushButton("修改", this);
    deleteBtn = new QPushButton("删除", this);
    undoBtn = new QPushButton("撤销", this);
    redoBtn = new QPushButton("恢复", this);
    // 设置按钮固定大小，保持一致性
    QList<QPushButton*> btns = {addBtn, editBtn, deleteBtn, undoBtn, redoBtn};
    for (auto btn : btns) {
        btn->setMinimumSize(70, 30);
    }
    inputLayout->addWidget(addBtn);
    inputLayout->addWidget(editBtn);
    inputLayout->addWidget(deleteBtn);
    inputLayout->addWidget(undoBtn);
    inputLayout->addWidget(redoBtn);

    mainLayout->addLayout(inputLayout);

    // 搜索布局
    QHBoxLayout* searchLayout = new QHBoxLayout();
    searchLayout->setSpacing(10);
    searchEdit = new QLineEdit(this);
    searchEdit->setPlaceholderText("按名称查询");
    searchEdit->setMinimumWidth(200);
    searchBtn = new QPushButton("查询", this);
    searchBtn->setMinimumSize(70, 30);
    searchLayout->addWidget(searchEdit);
    searchLayout->addWidget(searchBtn);
    mainLayout->addLayout(searchLayout);

    // 信息提示标签
    infoLabel = new QLabel(this);
    infoLabel->setMinimumHeight(25); // 预留足够高度显示信息
    mainLayout->addWidget(infoLabel);

    // 刷新表格数据
    refreshStationTable();

    // 信号连接
    connect(addBtn, &QPushButton::clicked, this, &StationAdminDialog::onAddStation);
    connect(deleteBtn, &QPushButton::clicked, this, &StationAdminDialog::onDeleteStation);
    connect(editBtn, &QPushButton::clicked, this, &StationAdminDialog::onEditStation);
    connect(searchBtn, &QPushButton::clicked, this, &StationAdminDialog::onSearchStation);
    connect(undoBtn, &QPushButton::clicked, this, [this]() {
        if (undoRedo.undoAction()) {
            refreshStationTable();
            showInfo("撤销成功");
        } else {
            showInfo("没有可撤销的操作");
        }
    });
    connect(redoBtn, &QPushButton::clicked, this, [this]() {
        if (undoRedo.redoAction()) {
            refreshStationTable();
            showInfo("恢复成功");
        } else {
            showInfo("没有可恢复的操作");
        }
    });

    // ===== 样式表设置（核心优化部分）=====
    // 主窗口背景
    setStyleSheet(R"(
        QDialog {
            background-color: #f5f7fa; /* 浅灰背景，避免刺眼 */
            color: #333333; /* 全局字体颜色（深灰），与背景对比清晰 */
        }

        /* 表格样式 */
        QTableWidget {
            background-color: white; /* 表格背景白色 */
            border: 1px solid #dddddd; /* 表格边框 */
            border-radius: 4px;
            gridline-color: #eeeeee; /* 网格线浅灰 */
        }
        QTableWidget::item {
            color: #333333; /* 表格内容字体色 */
            padding: 6px;
        }
        QTableWidget::item:selected {
            background-color: #e6f7ff; /* 选中行浅蓝色背景 */
            color: #000000; /* 选中行文字色（黑色，增强对比） */
        }
        QHeaderView::section {
            background-color: #2c3e50; /* 表头深灰背景 */
            color: white; /* 表头文字白色（对比强烈） */
            padding: 8px;
            border: none;
            font-weight: bold;
        }

        /* 输入框样式 */
        QLineEdit {
            background-color: white; /* 输入框白色背景 */
            color: #333333; /* 输入文字色 */
            border: 1px solid #cccccc;
            border-radius: 4px;
            padding: 5px 8px;
        }
        QLineEdit::placeholder-text {
            color: #999999; /* 提示文字浅灰，与输入文字区分 */
        }
        QLineEdit:focus {
            border-color: #3498db; /* 获焦时蓝色边框，提示状态 */
            outline: none;
        }

        /* 按钮样式 */
        QPushButton {
            background-color: #3498db; /* 主按钮蓝色 */
            color: white; /* 按钮文字白色（对比清晰） */
            border: none;
            border-radius: 4px;
            padding: 5px 10px;
        }
        QPushButton:hover {
            background-color: #2980b9; /* 悬停时加深颜色 */
        }
        QPushButton:pressed {
            background-color: #1f6dad; /* 按下时更深颜色 */
        }
        QPushButton#undoBtn {
            background-color: #f39c12; /* 撤销按钮橙色 */
        }
        QPushButton#undoBtn:hover {
            background-color: #e67e22;
        }
        QPushButton#undoBtn:pressed {
            background-color: #d35400;
        }
        QPushButton#redoBtn {
            background-color: #27ae60; /* 恢复按钮绿色 */
        }
        QPushButton#redoBtn:hover {
            background-color: #219653;
        }
        QPushButton#redoBtn:pressed {
            background-color: #1e8449;
        }

        /* 信息标签样式 */
        QLabel {
            color: #555555; /* 标签文字灰色，与背景区分 */
            padding: 4px;
        }
    )");

    // 给按钮设置对象名，确保样式表能正确匹配
    undoBtn->setObjectName("undoBtn");
    redoBtn->setObjectName("redoBtn");
}


void StationAdminDialog::refreshStationTable() {
    table->setRowCount(0);
    for (const auto& st : allData->stationsQueue) {
        int row = table->rowCount();
        table->insertRow(row);
        table->setItem(row, 0, new QTableWidgetItem(QString::number(st.getStationId())));
        table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(st.getName())));
    }
}

void StationAdminDialog::showInfo(const QString& msg) {
    infoLabel->setText(msg);
}

void StationAdminDialog::onAddStation() {
    bool okId;
    int id = idEdit->text().toInt(&okId);
    QString name = nameEdit->text().trimmed();
    if (!okId || name.isEmpty()) {
        showInfo("请输入合法的车站ID和名称");
        return;
    }
    for (const auto& st : allData->stationsQueue) {
        if (st.getStationId() == id || QString::fromStdString(st.getName()) == name) {
            showInfo("车站ID或名称已存在");
            return;
        }
    }
    stations newStation(id, name.toStdString());
    allData->stationsQueue.push_back(newStation);
	undoRedo.recordOp(Operation_s::makeSingle(Add, newStation, allData->stationsQueue.size() - 1));
    //allData->Station_WriteToFile("station.txt");
    refreshStationTable();
    showInfo("添加成功");
}

void StationAdminDialog::onDeleteStation() {
    QList<QTableWidgetItem*> selected = table->selectedItems();
    if (selected.isEmpty()) {
        showInfo("请选择要删除的车站");
        return;
    }
    int row = table->row(selected.first());
    int id = table->item(row, 0)->text().toInt();
    auto& queue = allData->stationsQueue;
    auto it = std::find_if(queue.begin(), queue.end(), [id](const stations& st) { return st.getStationId() == id; });
    if (it == queue.end()) {
        showInfo("车站不存在");
        return;
    }
	undoRedo.recordOp(Operation_s::makeSingle(Delete, *it, row));//这是一行删除的，多行参考用户管理的删除逻辑
    queue.erase(it);
    //allData->Station_WriteToFile("station.txt");
    refreshStationTable();
    showInfo("删除成功");
}

void StationAdminDialog::onEditStation() {
    QList<QTableWidgetItem*> selected = table->selectedItems();
    if (selected.isEmpty()) {
        showInfo("请选择要修改的车站");
        return;
    }
    int row = table->row(selected.first());
    int id = table->item(row, 0)->text().toInt();
    QString newName = nameEdit->text().trimmed();

    if (newName.isEmpty()) {
        showInfo("请输入新的车站名称");
        return;
    }
    for (auto it = allData->stationsQueue.begin(); it != allData->stationsQueue.end(); it++) {
        if (it->getName() == newName.toStdString()) {
			showInfo("车站名称已存在");
			return;
        }
    }
    auto& queue = allData->stationsQueue;
    auto it = std::find_if(queue.begin(), queue.end(), [id](const stations& st) { return st.getStationId() == id; });
    if (it == queue.end()) {
        showInfo("车站不存在");
        return;
    }
    stations old = *it;          // 复制旧对象

    it->setName(newName.toStdString());

    stations edited = *it;
    // —— 记录 —— 
    Operation_s op;
    op.type = Modify;
    op.Stations = { old, edited };  // 0 = 旧, 1 = 新
    op.indices = { row };
    undoRedo.recordOp(op);

    //allData->Station_WriteToFile("station.txt");
    refreshStationTable();
    showInfo("修改成功");
}

void StationAdminDialog::onSearchStation() {
    QString keyword = searchEdit->text().trimmed();
    table->setRowCount(0);
    for (const auto& st : allData->stationsQueue) {
        if (QString::fromStdString(st.getName()).contains(keyword)) {
            int row = table->rowCount();
            table->insertRow(row);
            table->setItem(row, 0, new QTableWidgetItem(QString::number(st.getStationId())));
            table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(st.getName())));
        }
    }
    showInfo("查询完成");
}
